package cn.fql.pet.service.impl;

import cn.fql.pet.domain.PetType;
import cn.fql.pet.mapper.PetTypeMapper;
import cn.fql.pet.service.IPetTypeService;
import cn.fql.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTree() {
        List<PetType> pets = petTypeMapper.findAll();
        //将所有部门查询出来 - 装到map集合 方便通过id找部门对象
        Map<Long, PetType> map = new HashMap<>();
        for (PetType petType : pets) {
            map.put(petType.getId(),petType);
        }
        List<PetType> petTree = new ArrayList<>();
        //遍历所有部门
        for (PetType petType : pets) {
            if(petType.getParentId() == null){//顶级部门
                //添加到部门树
                petTree.add(petType);
            }else{//有父级部门
                Long parent_id = petType.getParentId();//父部门id
                //获取父部门对象
                PetType parentPet = map.get(parent_id);
                if(parentPet != null){
                    //将自己状态父部门的children集合中
                    parentPet.getChildren().add(petType);
                }
            }
        }
        return petTree;
    }
}
